//引入api接口
import { reqshopList, reqDeletecart, reqUpdateCheckedById } from "@/api";

const state = {
    cartList: [],
}
const mutations = {
    GETCARTLIST(state, cartList) {
        state.cartList = cartList;
    }
}
const actions = {
    //获取购物车列表数据
    async shopList({ commit }) {
        let result = await reqshopList();
        if (result.code == 200) {
            commit("GETCARTLIST", result.data)
        }
    },
    //删除购物车某一个商品
    async deletecartListBySkuId({ commit }, skuId) {
        let result = await reqDeletecart(skuId);
        if (result.code == 200) {
            return "ok"
        } else {
            return Promise.reject(new Error("faile"))
        }
    },
    //修改购物车商品切换选中状态
    async updateCheckedById({ commit }, { skuId, isChecked }) {
        let result = await reqUpdateCheckedById(skuId, isChecked);
        if (result.code == 200) {
            return "ok";
        } else {
            return Promise.reject(new Error("faile"))
        }
    },
    //删除所有勾选的商品
    deleteAllCheckedCart({ dispatch, getters }) {
        //context这个小仓库
        //获取购物车中全部商品(是一个数组)
        let PromiseAll = [];
        getters.cartList.cartInfoList.forEach(item => {
            let promise =
                item.isChecked == 1
                    ? dispatch("deletecartListBySkuId", item.skuId) : "";
            //将一个返回的Promise添加到数组当中
            PromiseAll.push(promise);
        });
        //如果有一个失败了，返回即为失败的结果
        return Promise.all(PromiseAll)
    },
    //修改全部产品的状态
    UpdataAllCartChecked({ dispatch, state }, isChecked) {
        //数组
        let PromiseAll = [];
        state.cartList[0].cartInfoList.forEach((item) => {
            let promise = dispatch("updateCheckedById", { skuId: item.skuId, isChecked });
            PromiseAll.push(promise)
        });
        //最终返回的结果
        return Promise.all(PromiseAll);
    }
}
const getters = {
    cartList(state) {
        return state.cartList[0] || {};
    }
}
export default {
    state,
    mutations,
    actions,
    getters
}